package service

import (
	"blog-server/global"
	"blog-server/models"
	"blog-server/models/views"
	"blog-server/utils/msg"
	"log"
	"time"
	"xorm.io/xorm"
)

// CategoryService
type CategoryService struct{}

func NewCategoryService() *CategoryService {
	return &CategoryService{}
}

// CategorySelectAll 获取分类信息
func (category *CategoryService) CategorySelectAll() ([]models.Category, error) {
	var data []models.Category
	err := global.Engine.Select("id, title, brief, icon, sort_num").Where("can_view = ?", true).Desc("create_time").Desc("sort_num").Find(&data)
	if err != nil {
		return nil, msg.NewSysError(err.Error())
	}
	return data, nil
}

// CategoryPages 分页查询
func (category *CategoryService) CategoryPages(params views.CategoryPagesVo) (*msg.DataPage, error) {
	var data []models.Category
	var count int64
	condition := func(engine *xorm.Engine) *xorm.Session {
		session := engine.Table("blog_category").Where("can_view = true")
		if params.Title != "" {
			session.Where("title like %?%", params.Title)
		}
		if params.Page <= 0 {
			params.Page = 1
		}
		if params.Size <= 0 {
			params.Size = 10
		}
		return session
	}

	err := condition(global.Engine).Desc("create_time").Limit(params.Size, (params.Page-1)*params.Size).Find(&data)
	if err != nil {
		return &msg.DataPage{}, msg.NewSysError(err.Error())
	}
	count, err = condition(global.Engine).Count(&models.Category{})
	if err != nil {
		return &msg.DataPage{}, msg.NewSysError(err.Error())
	}
	return msg.NewDataPage(data, count, params.Page, params.Size), nil
}

// CategoryInsert 分类增加
func (category *CategoryService) CategoryInsert(params views.CategoryAddVo) (bool, error) {
	cate := new(models.Category)
	cate.Title = params.Title
	cate.Brief = params.Brief
	cate.UpdateTime = time.Now()
	cate.CreateTime = time.Now()
	cate.CanView = true
	if _, err := global.Engine.InsertOne(cate); err != nil {
		log.Println("增加文章分类失败", err.Error())
		return false, err
	}
	return true, nil
}

// CategoryUpdate 分类修改
func (category *CategoryService) CategoryUpdate(params views.CategoryUpdateVo) (bool, error) {

	var cate models.Category
	if _, err := global.Engine.ID(params.Id).Get(&cate); err != nil {
		return false, err
	}
	cate.Title = params.Title
	cate.Brief = params.Brief
	cate.UpdateTime = time.Now()

	if _, err := global.Engine.InsertOne(cate); err != nil {
		return false, err
	}
	return true, nil
}

func (category *CategoryService) CategoryDelete(ids []int) (bool, error) {
	if _, err := global.Engine.Table(&models.Category{}).In("id", ids).Update(map[string]interface{}{"can_view": false}); err != nil {
		log.Println("删除分类失败：", err.Error())
		return false, err
	}
	return true, nil
}
